package vsvm.math.statistics;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class McNeilCorrMatrix {
	
	private static final String dataFile = "/vsvm/resources/correlation.dat";
	
	private static ArrayList < ArrayList <Double> > matrix = null;
	private static ArrayList <Double> corrs = null;
	private static ArrayList <Double> aucs  = null;	
	
	public static double getCorrelation(double auc, double r) {
		if (matrix == null)
			loadMatrix();
		
		if (matrix == null) return 0;
		
		int i = 0;
		while (i < corrs.size() && r > corrs.get(i)) i++;
		if (i == corrs.size()) i--;
		
		int j = 0;
		while (j < aucs.size() && auc > aucs.get(j)) j++;
		if (j == aucs.size()) j--;
		
		return matrix.get(i).get(j);
	}
	
	private static void loadMatrix(){
		BufferedReader reader = null;
		try {
			InputStream s = McNeilCorrMatrix.class.getResourceAsStream(dataFile);
			//reader = new BufferedReader(new FileReader(dataFile));
			reader = new BufferedReader(new InputStreamReader(s));
		} catch (Exception ex) {
			System.out.println(System.getProperty("user.dir"));
			System.out.println("Can't find McNeil's correlation data file!");
			return;
		}
		
		String line = null;
		try {
			aucs   = new ArrayList();
			corrs  = new ArrayList();
			matrix = new ArrayList();
			
			line = reader.readLine();
			String[] vals = line.split(" ");
			for (int i = 0; i < vals.length; i++){
				if (vals[i].equals("")) continue;				
				aucs.add(Double.parseDouble(vals[i]));
			}
			
			while ( (line = reader.readLine()) != null ) {
				vals = line.split(" ");
				corrs.add(Double.parseDouble(vals[0]));
				ArrayList <Double> row = new ArrayList();
				for (int i = 1; i < vals.length; i++)
					row.add(Double.parseDouble(vals[i]));
				matrix.add(row);
			}
		} catch (IOException ex) {
			System.out.println("Problems reading McNeil's correlation data file");
			matrix = null;
			return;
		}
		
	}
}
